<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button type="primary" @click="handleAdd" icon="Plus">新增权限</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="permissionList"
      row-key="id"
      border
      default-expand-all
      :tree-props="{ children: 'children' }"
      style="width: 100%"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      :row-class-name="tableRowClassName"
      table-layout="auto"
    >
      <el-table-column prop="title" label="标题" min-width="150" align="center" show-overflow-tooltip />
      <el-table-column prop="name" label="名称" min-width="150" align="center" show-overflow-tooltip />
      <el-table-column prop="path" label="路径" min-width="180" align="center" show-overflow-tooltip />
      <el-table-column prop="orders" label="排序" width="80" align="center" />
      <el-table-column prop="isShow" label="是否显示" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.isShow === 1 ? 'success' : 'danger'" effect="light" size="small">
            {{ scope.row.isShow === 1 ? '显示' : '隐藏' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="150" align="center" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ formatDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="primary" link @click="handleAddChild(scope.row)">添加子权限</el-button>
          <el-popconfirm title="确定删除该权限吗?" @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改权限对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="permissionFormRef" :model="permissionForm" :rules="rules" label-width="100px">
        <el-form-item label="父级权限" prop="pid">
          <el-tree-select
            v-model="permissionForm.pid"
            :data="permissionOptions"
            :render-after-expand="false"
            node-key="id"
            :props="{ label: 'title', value: 'id' }"
            placeholder="选择父级权限"
            check-strictly
            clearable
          />
        </el-form-item>
        <el-form-item label="权限标题" prop="title">
          <el-input v-model="permissionForm.title" placeholder="请输入权限标题" />
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限路径" prop="path">
          <el-input v-model="permissionForm.path" placeholder="请输入权限路径" />
        </el-form-item>
        <el-form-item label="排序" prop="orders">
          <el-input-number v-model="permissionForm.orders" :min="0" />
        </el-form-item>
        <el-form-item label="是否显示" prop="isShow">
          <el-radio-group v-model="permissionForm.isShow">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPermissionTree, addPermission, updatePermission, deletePermission } from '@/api/permission'

// 权限列表数据
const permissionList = ref([])
// 权限选项，用于下拉选择父级权限
const permissionOptions = ref([])
// 加载状态
const loading = ref(false)
// 对话框可见性
const dialogVisible = ref(false)
// 对话框标题
const dialogTitle = ref('')
// 表单引用
const permissionFormRef = ref()
// 表单数据
const permissionForm = reactive({
  id: undefined,
  pid: 0,
  title: '',
  name: '',
  path: '',
  orders: 1,
  isShow: 1
})

// 表单校验规则
const rules = {
  title: [{ required: true, message: '请输入权限标题', trigger: 'blur' }],
  name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
  path: [{ required: true, message: '请输入权限路径', trigger: 'blur' }]
}

// 初始化获取数据
onMounted(() => {
  fetchPermissionTree()
})

// 获取权限树
const fetchPermissionTree = async () => {
  loading.value = true
  try {
    const { data } = await getPermissionTree()
    permissionList.value = data
    // 复制一份用于级联选择器
    permissionOptions.value = JSON.parse(JSON.stringify(data))
    // 在顶部添加一个"顶级权限"选项
    permissionOptions.value.unshift({ id: 0, title: '顶级权限', children: [] })
  } catch (error) {
    console.error('获取权限列表失败', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 添加权限
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '添加权限'
  dialogVisible.value = true
}

// 添加子权限
const handleAddChild = (row) => {
  resetForm()
  permissionForm.pid = row.id
  dialogTitle.value = `添加 "${row.title}" 的子权限`
  dialogVisible.value = true
}

// 更新权限
const handleUpdate = (row) => {
  resetForm()
  dialogTitle.value = '编辑权限'
  // 克隆对象，避免直接修改表格数据
  Object.assign(permissionForm, { ...row })
  dialogVisible.value = true
}

// 删除权限
const handleDelete = async (id) => {
  try {
    await deletePermission(id)
    ElMessage.success('删除成功')
    fetchPermissionTree()
  } catch (error) {
    console.error('删除失败', error)
    ElMessage.error('删除失败')
  }
}

// 提交表单
const submitForm = async () => {
  permissionFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (permissionForm.id) {
          // 更新
          await updatePermission(permissionForm)
          ElMessage.success('更新成功')
        } else {
          // 新增
          await addPermission(permissionForm)
          ElMessage.success('添加成功')
        }
        // 关闭对话框
        dialogVisible.value = false
        // 刷新数据
        fetchPermissionTree()
      } catch (error) {
        console.error('操作失败', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (permissionFormRef.value) {
    permissionFormRef.value.resetFields()
  }
  Object.assign(permissionForm, {
    id: undefined,
    pid: 0,
    title: '',
    name: '',
    path: '',
    orders: 1,
    isShow: 1
  })
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 表格行样式
const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 0 ? '' : 'row-stripe'
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 15px;
}

.app-container {
  width: 100%;
  height: 100%;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 15px 20px;
  box-sizing: border-box;
  width: 100%;
}

:deep(.el-table) {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
  width: 100% !important;
}

:deep(.el-table__inner-wrapper) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden !important;
}

.row-stripe {
  background-color: #fafafa;
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style> 